import 'dart:math';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/expert/expert_record_entity.dart';
import 'package:sports_new/entity/match/expert_views_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/server/api/expert_api.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/expert/expert_rate_chart.dart';
import 'package:sports_new/view/expert/items/plan_item.dart';
import 'package:sports_new/view/king/items/history_label.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import '../../../widgets/base/qkd_text.dart';
// import 'package:sports_new/view/pick/expert_list_item.dart';

class UserViewPointList extends StatefulWidget {
  //1 足球 2篮球
  final int type;
  final String expertId;
  final bool isShare;
  const UserViewPointList(this.type, this.expertId, {super.key,this.isShare = false});

  @override
  State<UserViewPointList> createState() => _UserViewPointListState();
}

class _UserViewPointListState extends State<UserViewPointList> with AutomaticKeepAliveClientMixin{
  List<PlanEntity>? planHistory;
  List<PlanEntity>? planNew;
  ExpertRecordEntity? record;
  EasyRefreshController refreshC =
      EasyRefreshController(controlFinishLoad: true);
  int page = 1;
  int pageSize = 30;

  final List<String> statusImage = [
    "",
    "viewpoint_status1.png",
    "viewpoint_status2.png",
    "viewpoint_status3.png",
    "viewpoint_status4.png",
    "viewpoint_status5.png",
    "viewpoint_status6.png",
    "viewpoint_status7.png"
  ];

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.isShare?Column(
      children: [
        if(ModeConfig.expertRecord)...[
          ExpertRateChart(
            expertId: widget.expertId, sportId: widget.type
          ),
          if (record?.achievement.hasValue == true)
          _expertRecordWidget(),
        ]
      ],
    ):MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: Container(
        color: Colours.greyF2F3F7,
        child: EasyRefresh(
          controller: refreshC,
          footer: Styles.refreshFooter(position: IndicatorPosition.locator),
          onRefresh: () async => await getData(),
          onLoad: () async => await getMore(),
          child: LoadingWidget<bool>(
            isLoading: planNew == null || planHistory == null,
            data: planNew?.length == 0 && planHistory?.length == 0,
            child: () => CustomScrollView(
              slivers: [
                if(ModeConfig.expertRecord)...[
                  SliverToBoxAdapter(
                    child: ExpertRateChart(
                      expertId: widget.expertId,
                      sportId: widget.type
                    )
                  ),
                  if (record?.achievement.hasValue == true)
                  SliverToBoxAdapter(child: _expertRecordWidget()),
                ],
                if (planNew.hasValue) ...[
                  SliverToBoxAdapter(
                    child: Container(
                      padding: const EdgeInsets.only(left: 12, top: 16),
                      margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                      decoration: const BoxDecoration(
                        color: Colours.white,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(8),
                          topRight: Radius.circular(8)
                        )
                      ),
                      child: QkdText("最新方案（${planNew?.length ?? 0}）",
                        fontSize: 16,
                        fontWeight: FontWeight.w600
                      ),
                    )
                  ),
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      childCount: planNew?.length ?? 0,
                      (context, index) {
                        return _expertNewViewsWidget(index);
                      }
                    )
                  ),
                ],
                if (planHistory.hasValue) ...[
                  SliverToBoxAdapter(
                    child: Container(
                      padding: const EdgeInsets.only(left: 12, top: 16),
                      margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                      decoration: const BoxDecoration(
                          color: Colours.white,
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(8),
                              topRight: Radius.circular(8))),
                      child: const QkdText("历史方案",
                        fontSize: 16,
                        fontWeight: FontWeight.w600
                      ),
                    ),
                  ),
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      childCount: planHistory!.length, (context, childIndex) {
                    return _expertHistoryViewsWidget(childIndex);
                  }))
                ],
                const FooterLocator.sliver(),
                SliverToBoxAdapter(child: Container(height: 80))
              ],
            ),
          ),
        ),
      ),
    );
  }

  getData() async {
    // if (page == 1) {
    //   planHistory = [];
    // }
    // List planHistory = [];
    ExpertApi.getExpertNewViews(widget.expertId, widget.type).then((value) {
      if (value != null) {
        planNew = value;
        update();
      }
    });
    ExpertApi.getExpertRecord(widget.expertId, widget.type).then((value) {
      if (value != null) {
        record = value;
        update();
      }
    });
    page = 1;
    final result = await ExpertApi.getPlanHistory(
        widget.expertId, widget.type, page, pageSize);
    if (result != null) {
      planHistory = result;
      refreshC.resetFooter();
    }

    update();
  }

  getMore() async {
    page++;
    final result = await ExpertApi.getPlanHistory(
        widget.expertId, widget.type, page, pageSize);
    if (result != null) {
      planHistory!.addAll(result);
      refreshC.finishLoad(result.length < pageSize
          ? IndicatorResult.noMore
          : IndicatorResult.success);
      update();
    }
  }

  Widget _expertRecordWidget() {
    var list = [
      record!.redKeep == null || record!.redKeep == '' || record!.redKeep == '-'
          ? '-'
          : record!.redKeep,
      record!.backRatio == null ||
              record!.backRatio == '' ||
              record!.backRatio == '-'
          ? '-'
          : "${double.parse(record!.backRatio!).toInt()}%",
      record!.redKeepHigh == null ||
              record!.redKeepHigh == '' ||
              record!.redKeepHigh == '-'
          ? '-'
          : record!.redKeepHigh,
    ];
    List<String> recordTypeList = ["当前状态", "近n场回报", "最高连红"];
    return Block(
      cardStyle: const CardStyle(
        padding: EdgeInsets.all(16),
        margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          QkdText("${widget.type == 1 ? "足球" : "篮球"}战绩",
            fontSize: 16,
            fontWeight: FontWeight.w600
          ),
          Container(height: 9),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List<Widget>.generate(3,
              (childIndex) => Expanded(
                child: Container(
                  height: 66,
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  decoration: BoxDecoration(
                    color: Colours.greyF5F7FA,
                    borderRadius: BorderRadius.circular(5.0),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      QkdText(list[childIndex]!,
                        fontSize: 16,
                        color: Colours.main,
                        fontWeight: FontWeight.w500
                      ),
                      QkdText(
                        childIndex == 1
                          ? "近${record!.backRatioM ?? "n"}场回报"
                          : recordTypeList[childIndex],
                        fontSize: 12
                      )
                    ],
                  ),
                ),
              )
            ).insertEvery(Container(width: 8)),
          ),
          Container(height: 7),
          if (record?.achievement.hasValue == true)
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              physics: const ClampingScrollPhysics(),
              child: Row(
                children: List.generate(
                  record!.achievement!.length,
                  (index) => Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: _buildAchievementList(index),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _expertNewViewsWidget(int index) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      clipBehavior: Clip.hardEdge,
      decoration: BoxDecoration(
        color: Colours.white,
        borderRadius: index == planNew!.length - 1
            ? const BorderRadius.only(
                bottomLeft: Radius.circular(8),
                bottomRight: Radius.circular(8))
            : null),
      child: Column(
        children: [
          PlanItem(
            isExpertDetailView: true, entity: planNew![index]),
          if (index != planNew!.length - 1)
          Container(
            height: 0.5,
            width: double.infinity,
            color: Colours.greyEE,
          )
        ],
      )
    );
  }

  Widget _expertHistoryViewsWidget(int index) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 8),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      clipBehavior: Clip.hardEdge,
      decoration: BoxDecoration(
        color: Colours.white,
        borderRadius: index == planHistory!.length - 1
            ? const BorderRadius.only(
                bottomLeft: Radius.circular(8),
                bottomRight: Radius.circular(8))
            : null),
      child: Column(
        children: [
          PlanItem(
            isExpertDetailView: true,
            entity: planHistory![index],
            eventType: "expert_detail_plan_view",
          ),
          if (index != planHistory!.length - 1)
            Container(
              height: 0.5,
              width: double.infinity,
              color: Colours.greyEE,
            )
        ],
      )
    );
  }

  Widget _buildAchievementList(int childIndex) {
    var achievement = record!.achievement![childIndex];
    return Transform.rotate(
      angle: pi/6,
      child: HistoryLabel.viewpointRecord(
        state: achievement.status,
        width: 28,fontSize: 10,
      ).tap(() => Get.toNamed(Routes.viewpoint, arguments: achievement.planId)),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
